/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package delta.cart.bean;

import entity.Product;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import javax.ejb.Stateful;

/**
 *
 * @author Kate
 */
@Stateful
public class Cart implements CartLocal {

    HashMap<Product, Integer> productList;

    @PostConstruct
    public void postConstruct() {
        productList = new HashMap();
    }

    @Override
    public void addProduct(Product product, int quantity) throws InvalidQuantityException,
            InvalidPriceException {


        if (quantity < 1 || quantity > 1000000000) {
            throw new InvalidQuantityException();
        }

        Integer count;
        float expectedPrice;
            expectedPrice = (getTotalPrice() + product.getPrice() * quantity );
            
        if (expectedPrice> 99999) {
            throw new InvalidPriceException();
        }
        if (productList.containsKey(product)) {
            count = productList.get(product);
            count += quantity;
        } else {
            count = quantity;
        }

        productList.put(product, count);

    }

    public int getCount() {
        int count = 0;
        for (Integer i : productList.values()) {
            count += i;
        }
        return count;
    }

    public float getTotalPrice() {
        float totalPrice = 0;
        for (Product product : productList.keySet()) {
            totalPrice += productList.get(product) * product.getPrice();
        }

        return totalPrice;


    }

    public HashMap<Product, Integer> getProductList() {

        return productList;
    }

    public void remove(Product product) {
        productList.remove(product);
    }

    public void removeAll() {
        productList.clear();
    }

    @Override
    public void setQuantity(Product product, int quantity) throws InvalidQuantityException,
            InvalidPriceException {
        if (quantity < 1 || quantity > 1000000000) {
            throw new InvalidQuantityException();
        }

        if ((getTotalPrice() + product.getPrice() * (quantity-productList.get(product))) > 99999) {
            throw new InvalidPriceException();
        }
        productList.put(product, quantity);

    }
}
